<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
<!--      <el-form-item label="天猫账号" prop="jhAccount">-->
<!--        <el-input v-model="queryParams.jhAccount" clearable placeholder="请输入天猫账号" @keyup.enter.native="handleQuery"/>-->
<!--      </el-form-item>-->
      <el-form-item label="店铺名称" prop="jhName">
        <el-input v-model="queryParams.jhName" clearable placeholder="请输入店铺名称" @keyup.enter.native="handleQuery"/>
      </el-form-item>
<!--      <el-form-item label="会员身份" prop="jhIdentity">-->
<!--        <el-input v-model="queryParams.jhIdentity" clearable placeholder="请输入会员身份" @keyup.enter.native="handleQuery"/>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="到期时间" prop="jhEnddate">-->
<!--        <el-date-picker v-model="dateRange" end-placeholder="结束日期" range-separator="-" start-placeholder="开始日期" style="width: 240px" type="daterange"-->
<!--                        value-format="yyyy-MM-dd"></el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:account:add']" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:account:edit']" :disabled="single" icon="el-icon-edit" plain size="mini" type="success" @click="handleUpdate">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:account:remove']" :disabled="multiple" icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:account:export']" icon="el-icon-download" plain size="mini" type="warning" @click="handleExport">
          导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="60"/>
<!--      <el-table-column align="center" label="天猫账号" prop="jhAccount"/>-->
      <el-table-column align="center" label="店铺名称" prop="jhName"/>
      <el-table-column align="center" label="AppKey" prop="jhAppKey"/>
      <el-table-column align="center" label="AppSecret" prop="jhAppSecret"/>
      <el-table-column align="center" label="回调地址特征" prop="jhFeature"/>
      <!--      <el-table-column align="center" label="会员身份" prop="jhIdentity"/>-->
<!--      <el-table-column align="center" label="到期时间" prop="jhEnddate" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.jhEnddate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column align="center" label="授权状态">
        <template slot-scope="scope">
          {{ scope.row.jhStatus === "1" ? '已授权' : '未授权' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="加油包" prop="jhTrafficNum"/>
      <el-table-column align="center" label="每日复制数量" prop="jhCopyNum"/>
<!--      <el-table-column align="center" label="登录时间" prop="jhLoginTime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.jhLoginTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="160">
        <template slot-scope="scope">
          <!--          // 授权页面，暂时写死，如果不写死的话，需要保存 appkey;secret;client_id; ps: 不知道过期时间-->
          <!--          // redirect_uri 这个也需要改-->
          <el-button v-hasPermi="['jihuo:account:edit']" icon="el-icon-edit" size="mini"
                     type="text"
                     @click="goTarget(scope.row)">
            授权
          </el-button>
          <el-button v-hasPermi="['jihuo:account:edit']" icon="el-icon-edit" size="mini" type="text"
                     @click="openPage('traffic')">充值
          </el-button>
<!--          <el-button v-hasPermi="['jihuo:account:edit']" icon="el-icon-edit" size="mini" type="text"-->
<!--                     @click="showTransfer(scope.row)">转移-->
<!--          </el-button>-->
          <el-button v-hasPermi="['jihuo:account:edit']" icon="el-icon-edit" size="mini" type="text"
                     @click="showConfigUpdate(scope.row)">设置
          </el-button>
          <el-button v-hasPermi="['jihuo:account:remove']" icon="el-icon-delete" size="mini" type="text"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 添加或修改天猫账户对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="550px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
<!--        <el-form-item label="天猫账号" prop="jhAccount">-->
<!--          <el-input v-model="form.jhAccount" placeholder="请输入天猫账号"/>-->
<!--        </el-form-item>-->
        <el-form-item label="店铺名称" prop="jhName">
          <el-input v-model="form.jhName" placeholder="请输入店铺名称"/>
        </el-form-item>
        <el-form-item label="AppKey" prop="jhAppKey">
          <el-input v-model="form.jhAppKey" placeholder="请输入AppKey"/>
        </el-form-item>
        <el-form-item label="AppSecret" prop="jhAppSecret">
          <el-input v-model="form.jhAppSecret" placeholder="请输入AppSecret"/>
        </el-form-item>
        <el-form-item label="特征" prop="jhFeature">
          <el-input v-model="form.jhFeature" placeholder="请输入回调地址特征" :disabled="jhFeatureIsDisable"/>
        </el-form-item>
<!--        <el-form-item label="会员身份" prop="jhIdentity">-->
<!--          <el-input v-model="form.jhIdentity" placeholder="请输入会员身份"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="Session" prop="jhAppSession">-->
<!--          <el-input v-model="form.jhAppSession" placeholder="请输入session"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="到期时间" prop="jhEnddate">-->
<!--          <el-date-picker v-model="form.jhEnddate" clearable placeholder="请选择到期时间" type="date"-->
<!--                          value-format="yyyy-MM-dd">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改设置对话框 -->
    <el-dialog :title="title" :visible.sync="config" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="每日复制数量" prop="jhCopyNum">
          <el-input v-model="form.jhCopyNum" placeholder="请输入每日复制数量"/>
        </el-form-item>
        <el-form-item label="上架设置">
          <el-radio-group v-model="form.jhListingSet">
            <el-radio v-for="dict in dict.type.jh_listing_set" :key="dict.value" :label="dict.value">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="检测重复">
          <el-radio-group v-model="form.jhRepeatSet">
            <el-radio v-for="dict in dict.type.jh_repeat_set" :key="dict.value" :label="dict.value">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 转移流量对话框 -->
    <el-dialog :title="title" :visible.sync="transfer" append-to-body width="1000px">
      <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
<!--        <el-form-item label="天猫账号" prop="jhAccount">-->
<!--          <el-input v-model="queryParams.jhAccount" clearable placeholder="请输入天猫账号" @keyup.enter.native="handleQuery"/>-->
<!--        </el-form-item>-->
        <el-form-item label="店铺名称" prop="jhName">
          <el-input v-model="queryParams.jhName" clearable placeholder="请输入店铺名称" @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"/>
<!--        <el-table-column align="center" label="天猫账号" prop="jhAccount"/>-->
        <el-table-column align="center" label="店铺名称" prop="jhName"/>
<!--        <el-table-column align="center" label="会员身份" prop="jhIdentity"/>-->
<!--        <el-table-column align="center" label="到期时间" prop="jhEnddate" width="180">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.jhEnddate, '{y}-{m}-{d}') }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column align="center" label="加油包" prop="jhTrafficNum"/>
      </el-table>

      <pagination v-show="total>0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
                  @pagination="getList"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleTransferTraffic">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addAccount, checkAuthorization, delAccount, getAccount, listAccount, transferTraffic, updateAccount} from "@/api/jihuo/account";

export default {
  name: "Account",
  dicts: ['jh_listing_set', 'jh_repeat_set'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 天猫账户表格数据
      accountList: [],
      // 弹出层标题
      title: "",
      //是否禁用
      jhFeatureIsDisable:false,
      // 日期范围
      dateRange: "",
      // 是否显示弹出层
      open: false,
      config: false,
      transfer: false,
      // 转移流量的原始账号id todo 应该将其设置为局部变量，而不是全局变量
      originalId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jhAccount: null,
        jhName: null,
        jhIdentity: null,
        jhEnddate: null,
        jhStatus: null,
        jhTrafficNum: null,
        jhCopyNum: null,
        jhLoginTime: null,
        jhListingSet: null,
        beginJhEnddate: null,
        endJhEnddate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jhAccount: [
          {required: true, message: "天猫账号不能为空", trigger: "blur"}
        ],
        jhName: [
          {required: true, message: "店铺名称不能为空", trigger: "blur"}
        ],
        jhIdentity: [
          {required: true, message: "会员身份不能为空", trigger: "blur"}
        ],
        jhEnddate: [
          {required: true, message: "到期时间不能为空", trigger: "blur"}
        ],
        jhStatus: [
          {required: true, message: "授权状态不能为空", trigger: "change"}
        ],
        jhTrafficNum: [
          {required: true, message: "加油包不能为空", trigger: "blur"}
        ],
        jhAppSecret: [
          {required: true, message: "AppSecret不能为空", trigger: "blur"}
        ],
        jhAppKey: [
          {required: true, message: "AppKey不能为空", trigger: "blur"}
        ],
        jhFeature: [
        {required: true, message: "回调地址特征不能为空", trigger: "blur"}
      ]
        // jhAppSession: [
        //   {required: true, message: "Session不能为空", trigger: "blur"}
        // ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询天猫账户列表 */
    getList() {
      this.loading = true;
      listAccount(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.config = false;
      this.transfer = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jhId: null,
        jhRevision: null,
        jhCreatedBy: null,
        jhCreatedTime: null,
        jhUpdatedBy: null,
        jhUpdatedTime: null,
        jhAccount: null,
        jhPassword: null,
        jhName: null,
        jhIdentity: null,
        jhEnddate: null,
        jhStatus: null,
        jhTrafficNum: null,
        jhCopyNum: null,
        jhLoginTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jhId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.jhFeatureIsDisable = false;
      this.title = "添加天猫账户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const jhId = row.jhId || this.ids
      getAccount(jhId).then(response => {
        this.form = response.data;
        this.open = true;
        this.jhFeatureIsDisable = true;
        this.title = "修改天猫账户";
      });
    },
    /** 弹出设置修改页面 */
    showConfigUpdate(row) {
      this.reset();
      const jhId = row.jhId || this.ids
      getAccount(jhId).then(response => {
        this.form = response.data;
        this.config = true;
        this.title = "设置修改";
      });
    },
    /** 弹出转移流量页面 */
    showTransfer(row) {
      this.reset();
      const jhId = row.jhId || this.ids
      listAccount().then(response => {
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.originalId = jhId;
        this.transfer = true;
        this.title = "转移流量";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.jhId != null) {
            updateAccount(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.config = false;
              this.transfer = false;
              this.getList();
            });
          } else {
            addAccount(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.config = false;
              this.transfer = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jhIds = row.jhId || this.ids;
      this.$modal.confirm('是否确认删除天猫账户编号为"' + jhIds + '"的数据项？').then(function () {
        return delAccount(jhIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jihuo/account/export', {
        ...this.queryParams
      }, `account_${new Date().getTime()}.xlsx`)
    },
    /** 转移流量按钮操作 */
    handleTransferTraffic(row) {
      this.reset();
      const jhId = row.jhId || this.ids;
      if (jhId && jhId.length > 1) {
        alert("只能选择一个账号");
        return;
      }
      transferTraffic(this.originalId, jhId[0]).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.config = false;
        this.transfer = false;
        this.originalId = null;
        this.getList();
      });
    },
    openPage(href) {
      this.$router.push({path: href});
    },
    goTarget(row) {
      //在authCallback后面拼接上/row.jhId
      const href = 'https://oauth.taobao.com/authorize?response_type=code&client_id=' + row.jhAppKey + '&redirect_uri=http://47.105.60.76:8081/jihuo/authCallback/' + row.jhFeature + '&force_auth=true&from_site=fuwu';
      const jhId = row.jhId || this.ids;
      const newWindow = window.open(href, "_blank");
      const timer = setInterval(() => {
        if (newWindow.closed) {
          clearInterval(timer);
          this.checkAuthorizationStatus(jhId);
        }
      }, 1000);
    },
    checkAuthorizationStatus(jhId) {
      checkAuthorization(jhId).then(response => {
        if (response.code == 200) {
          this.$modal.msgSuccess("授权完成");
        } else {
          this.$modal.msgError("需要重新授权");
        }
      }).catch(() => {
        this.$modal.msgError("授权检查失败，请重试");
      });
    },
  }
};
</script>
